/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
 * 02111-1307, USA.
 *
 * http://www.gnu.org/copyleft/gpl.html
 */
package l1j.server.server.clientpackets;

import java.io.IOException;//TODO 記錄文件檔 by 阿傑
import java.io.BufferedWriter;//TODO 記錄文件檔 by 阿傑
import java.io.FileWriter;//TODO 記錄文件檔 by 阿傑
import java.sql.Timestamp;//TODO 記錄文件檔 by 阿傑

import l1j.opqlo.NewSystem.各項記錄輸出;
import l1j.opqlo.Server.L1World.L1World;
import l1j.server.echo.ClientThread;
import l1j.server.server.ActionCodes;
import l1j.server.server.model.L1Inventory;
import l1j.server.server.model.L1Object;
import l1j.server.server.model.Instance.L1ItemInstance;
import l1j.server.server.model.Instance.L1PcInstance;
import l1j.server.server.model.item.L1ItemId;
import l1j.server.server.serverpackets.S_AttackPacket;
import l1j.server.server.serverpackets.S_ServerMessage;
import l1j.server.server.utils.StreamUtil;

import java.util.logging.Level;
import java.util.logging.Logger;
/**
 * 處理收到由客戶端傳來撿起道具的封包
 */
public class C_PickUpItem extends ClientBasePacket {

	private static final String C_PICK_UP_ITEM = "[C] C_PickUpItem";
	private static final Logger _log = Logger.getLogger(C_PickUpItem.class.getName());
	//TODO 記錄文件檔 by 阿傑
	public static void pickupitem(String info) {
		BufferedWriter out = null;
		try {
			out = new BufferedWriter(new FileWriter("pickupitem.txt", true));
			out.write(info + "\r\n");
		} catch (final IOException e) {
			_log.log(Level.SEVERE , e.getLocalizedMessage() , e);
		}finally{
			StreamUtil.close(out);
		}
	}
	@Override
	public String getType() {
		return C_PICK_UP_ITEM;
	}
	@Override
	public void start(final byte[] decrypt, final ClientThread client) {
		try {
			// 資料載入
			this.read(decrypt);

			final L1PcInstance pc = client.getActiveChar();
			if (pc == null || pc.isDead() || pc.isGhost()) {
				return;
			}

			final int x = this.readH();
			final int y = this.readH();
			final int objectId = this.readD();
			int pickupCount = this.readD();

			//opqlo 防洗
			pickupCount = Math.abs(pickupCount);
			pickupCount = Math.min(pickupCount,2000000000);
			//opqlo 防洗

			//TODO 魔法娃娃DB化
			if ( objectId == pc.getId()) {
				//TODO 魔法娃娃DB化
				return;
			}
			if (pc.isInvisble()) { // 隱身狀態
				return;
			}
			if (pc.isInvisDelay()) { // 還在解除隱身的延遲
				return;
			}

			final L1Inventory groundInventory = L1World.getInstance().getInventory(x, y,pc.getMapId());
			final L1Object object = groundInventory.getItem(objectId);

			if (object != null && !pc.isDead()) {
				final L1ItemInstance item = (L1ItemInstance) object;

				//opqlo 防洗
				if(pickupCount > 0 && pickupCount < 2000000000
						&& item.getCount() > 0 && item.getCount() >= pickupCount)
				{
					//opqlo 防洗

					if (item.getItemOwnerId() != 0
							&& pc.getId() != item.getItemOwnerId()) {
						pc.sendPackets(new S_ServerMessage(623)); // アイテムが拾えませんでした。
						return;
					}
					if (pc.getLocation().getTileLineDistance(item.getLocation()) > 3) {
						return;
					}

					if (item.getItem().getItemId() == L1ItemId.ADENA) {
						final L1ItemInstance inventoryItem = pc.getInventory().findItemId(L1ItemId.ADENA);
						long inventoryItemCount = 0;
						if (inventoryItem != null) {
							inventoryItemCount = inventoryItem.getCount();
						}
						// 拾った後に2Gを超過しないようにチェック
						if (inventoryItemCount + pickupCount > 2000000000L) {
							pc.sendPackets(new S_ServerMessage(166, // \f1%0が%4%1%3%2
									"所持有的金幣", "超過 20億 了！無法再取得更多。"));
							return;
						}
					}

					if (pc.getInventory().checkAddItem( // 容量重量確認及びメッセージ送信
							item, pickupCount) == L1Inventory.OK) {
						if (item.getX() != 0 && item.getY() != 0) { // ワールドマップ上のアイテム
							groundInventory.tradeItem(item, pickupCount,pc.getInventory());
							pc.turnOnOffLight();

							pc.sendPackets(new S_AttackPacket(pc, objectId,ActionCodes.ACTION_Pickup));
							if (!pc.isGmInvis()) {
								pc.broadcastPacketAll(new S_AttackPacket(pc, objectId,ActionCodes.ACTION_Pickup));
							}
						}
					}

					final StringBuilder log = new StringBuilder();
					log.append("IP(").append(pc.getNetConnection().getIp().toString()).append(")	玩家:【").append(pc.getName()).append("】		拾取【")
					.append(item.getViewName()).append("】		流水號:").append(item.getId()).append("	時間:(").append( new Timestamp(System.currentTimeMillis())).append(")。");
					 各項記錄輸出.LogSave(27, log.toString());
					 log.delete(0, log.length());
					//opqlo 防洗
				}else{
					_log.info("[c]PickUpItem 防洗踢除 "+client.getAccountName());
					client.close();
				return;}
				//opqlo 防洗
			}

		} catch (final Exception e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);

		} finally {
			this.over();
		}

	}
}
